package com.tanhua.server.interceptor;

import cn.hutool.core.codec.Base64Decoder;
import com.alibaba.fastjson.JSON;
import com.tanhua.common.util.JwtUtils;
import com.tanhua.model.domain.User;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author : xyiaao
 * @createDate : 2022/3/16 20:10
 */
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String, Long> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        redisTemplate.opsForValue();
        String token = request.getHeader("Authorization");
        if (JwtUtils.verifyToken(token)) {
            log.info("uri---------->" + request.getMethod() + "---------->" + request.getRequestURI());
            // token合法，将token保存到redis中，时效5分钟
            redisTemplate.opsForValue().set(token, System.currentTimeMillis(), 5, TimeUnit.MINUTES);
            Claims claims = JwtUtils.getClaims(token);
            User user = new User();
            user.setId(Long.valueOf((Integer) claims.get("id")));
            user.setMobile((String) claims.get("mobile"));
            UserHolder.set(user);
            return true;
        }
        if (JwtUtils.isExpired(token)) {
            // token已过期
            Long lastTime = redisTemplate.opsForValue().get(token);
            // 判断redis中会否存在该token记录(5分钟时效)
            if (lastTime != null) {
                // 获取token中载荷内容
                // String[] strings = token.split("\\.");
                // String payload = strings[1];
                String payload = token.substring(token.indexOf(".") + 1, token.lastIndexOf("."));
                String json = Base64Decoder.decodeStr(payload, StandardCharsets.UTF_8);
                HashMap hashMap = JSON.parseObject(json, HashMap.class);
                // 重新生成一个token
                token = JwtUtils.getToken(hashMap);
                // 通过response返回
                response.setStatus(206);
                response.setHeader("Authorization", token);
            }
        }
        response.setStatus(401);
        return false;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        UserHolder.remove();
    }

}
